package com.hjq.fcloud.ui.activity

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import com.hjq.fcloud.R
import com.hjq.fcloud.bean.FileItemBean
import com.hjq.fcloud.bean.FlowDataBean
import com.hjq.fcloud.bean.MettingData
import com.hjq.fcloud.config.SystemSet
import com.hjq.fcloud.event.EventBean
import com.hjq.fcloud.event.EventBusUtils
import com.hjq.fcloud.http.api.MaterialsWarehousingConfirmationDetailApi
import com.hjq.fcloud.http.api.MaterialsWarehousingConfirmationSubmitApi
import com.hjq.fcloud.http.model.HttpData
import com.hjq.fcloud.jump.CommonJumpBean
import com.hjq.fcloud.ktx.ViewKtx.setVisibility
import com.hjq.fcloud.other.MaterialsDetailHandler
import com.hjq.fcloud.other.SelectedImageViewHelper
import com.hjq.fcloud.other.SignRefershHelper
import com.hjq.fcloud.widget.BottomSignViewClickListener
import com.hjq.fcloud.widget.StoreConfirmImageView
import com.hjq.http.EasyHttp
import com.hjq.http.body.JsonBody
import com.hjq.http.listener.HttpCallback
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.batchSb
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.batchTimeSb
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.bottomView
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.imageUploadView
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.horizontalScrollItemView
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.feedbackRootView
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.feedbackView
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.flowView
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.moneySb
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.numberSb
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.projectSb
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.sectionNameSb
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.statusLayout
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.storeConfrimIv
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.supplierNameSb
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.totalPriceSb
import kotlinx.android.synthetic.main.activity_materials_warehousing_confirmation.totalSb
import okhttp3.Call
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 材料入库确认
 */
class MaterialsWarehousingConfirmationActivity : BaseDetailActivity() {

    companion object {
        //确认结果0未通过1通过
        const val STATUS_PASS = "1"
        const val STATUS_NOT_PASS = "0"

        const val KEY_IMAGE = "fnc-230-1"

        fun start(ac: Context, jumpBean: CommonJumpBean, isDisableAgainSign: Boolean = false) {
            var intent = Intent(ac, MaterialsWarehousingConfirmationActivity::class.java)
            intent.putExtra(INTENT_IN_ITEM, jumpBean)
            intent.putExtra(INTENT_IN_DISABLE_AGAIN_SIGN, isDisableAgainSign)
            ac.startActivity(intent)
        }
    }

    private var status: String = STATUS_PASS

    //由服务器告诉客户端客户端是否需要传（99表示平台方）
    val needUploadImage by lazy { SystemSet.config?.info?.corp_type.equals("99") }

    private var mDetail: MaterialsWarehousingConfirmationDetailApi.Data? = null
    var mSelectedImageViewHelper = SelectedImageViewHelper()

    override fun userEventBus(): Boolean {
        return true
    }

    override fun getStateLayout(): View? {
        return statusLayout
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_materials_warehousing_confirmation
    }

    override fun initView() {

    }

    override fun initData() {
        getServerFlow()

        getServerFlowStatus({ flowStatusBean ->
            getServerDetail()

            if (flowStatusBean.canSign || flowStatusBean.canAgainSign) {
                var isAgainSign = flowStatusBean.canAgainSign && !isDisableAgainSign//重新签约
                if (isAgainSign) {//需要展示流程传控件
                    flowView.setVisibility(true)
                } else {
                    //审核控件设置
                    feedbackRootView.setVisibility(true)

                    initImageViewSelect(true)
                }
                //底部签约控件设置
                bottomView.setViewData(isAgainSign, object :
                    BottomSignViewClickListener {
                    override fun onAgainPassSign() {
                        requestServerResetFlow() {
                            start(context, commonJumpBean!!, true)
                            finish()
                        }
                    }

                    override fun onPassSign() {
                        status = STATUS_PASS
                        if (checkInput()) {
                            FaceDetectRGBActivity.launcher(context, intent.extras)
                        }
                    }

                    override fun onNoPassSign() {
                        status = STATUS_NOT_PASS
                        if (checkInput()) {
                            FaceDetectRGBActivity.launcher(context, intent.extras)
                        }
                    }

                })
            } else {
                flowView.setVisibility(true)
            }
        })
    }

    override fun handlerFlowRequestParms(parms: HashMap<String, Any?>) {
        parms.put("biz_type", "store")
    }

    override fun handlerFlowStatusRequestParms(parms: HashMap<String, Any?>) {
        parms.put("fnc_id", "")
        parms.put("type", "store")
        parms.put("id", commonJumpBean?.bizId)
    }

    /**
     * 材料入库相关图片
     */
    private fun initImageViewSelect(canEdit: Boolean, data: ArrayList<FileItemBean>? = null) {
        let {
            if(needUploadImage){
                imageUploadView.apply {
                    setVisibility(true)
                    setCanEdit(canEdit)
                    if(canEdit){
                        getSettingBar().setLeftDrawable(R.drawable.ic_star)
                    }
                    getSettingBar().setLeftText("材料入库相关图片")
                    mSelectedImageViewHelper.initSelectedImageView(
                        this@MaterialsWarehousingConfirmationActivity,
                        getSelectedImageView(),
                        IMAGE_MAX_SELECT
                    )
                    mSelectedImageViewHelper.setData(data)
                }
            }
        }
    }

    private fun checkInput(): Boolean {
        if (needUploadImage && imageUploadView.getSelectedImageView().data.size == 0) {
            showToast("请上传材料入库相关图片")
            return false
        }

        var reason = feedbackView.getInPutText()
        if (TextUtils.isEmpty(reason)) {
            showToast("请输入意见反馈")
            return false
        }
        return true
    }


    override fun setFlowViewData(data: FlowDataBean?) {
        flowView.setViewData(data?.setup_list)
    }

    private fun getServerDetail() {
        var api = MaterialsWarehousingConfirmationDetailApi()
            .setId(commonJumpBean?.bizId)
        EasyHttp.post(this)
            .api(api)
            .request(object :
                HttpCallback<HttpData<MaterialsWarehousingConfirmationDetailApi.Data?>?>(this) {
                override fun onStart(call: Call?) {}
                override fun onSucceed(data: HttpData<MaterialsWarehousingConfirmationDetailApi.Data?>?) {
                    mDetail = data?.getData()
                    setViewData(mDetail)
                }

                override fun onEnd(call: Call?) {
                    super.onEnd(call)
                    showAppContent()
                }
            })
    }

    private fun setViewData(data: MaterialsWarehousingConfirmationDetailApi.Data?) {
        showAppContent()

        var mainStatus = data?.main_status
        if (mainStatus.equals(StoreConfirmImageView.CONFIRM_SUCCESS)) {
            initImageViewSelect(false, data?.files?.get(KEY_IMAGE))
        }
        storeConfrimIv.setViewData(mainStatus)
        numberSb.setRightText(data?.fnc?.code)
        projectSb.setRightText(data?.fnc?.project?.project_name)
        sectionNameSb.setRightText(data?.fnc?.sect?.sect_name)
        moneySb.setRightText(data?.fnc?.money)
        supplierNameSb.setRightText(data?.fnc?.supply_corp?.corp_name)
        batchSb.setRightText(data?.batch_no)
        batchTimeSb.setRightText(data?.store_time)
        totalSb.setRightText(data?.money)

        //材料明细
        horizontalScrollItemView.setViewData(MaterialsDetailHandler.buildMaterialsDetailList(data?.dtls))
        totalPriceSb.setLeftText("本次进场材料总计金额：".plus(data?.money))
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMainEventBus(bean: EventBean) {
        if (bean != null && bean.type == EventBusUtils.TYPE_FACE_AND_SIGN_FINISH) {
            var signParms = bean.parms as HashMap<String, String?>

            uploadFileAndSubmit(signParms)
        }
    }

    private fun uploadFileAndSubmit(signParms: HashMap<String, String?>) {
        var parms = HashMap<String, Any?>()
        parms.putAll(signParms)
        //图片
        var uploadSuccessList = mSelectedImageViewHelper.getData()
        var fileMap = HashMap<String, Any>()
        fileMap.put(KEY_IMAGE, getRequestFileList(uploadSuccessList))
        parms.put("files", fileMap)

        requestServerSubmit(parms)
    }

    private fun requestServerSubmit(parms: HashMap<String, Any?>) {
        parms.put("id", mDetail?.id)
        parms.put("reason", feedbackView.getInPutText())
        parms.put("result", status)
        EasyHttp.post(this)
            .api(MaterialsWarehousingConfirmationSubmitApi())
            .body(JsonBody(parms))
            .request(object : HttpCallback<HttpData<MettingData?>?>(this) {
                override fun onSucceed(data: HttpData<MettingData?>?) {
                    SignRefershHelper.signSuccessRefersh(context, commonJumpBean)
                    showToast(data?.getMessage())
                }
            })
    }
}